package qianting.news.article.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import qianting.news.apis.models.article.dtos.CollectionBehaviorDto;
import qianting.news.common.entity.AuthUser;
import qianting.news.common.utils.AppThreadLocalUtil;
import qianting.news.article.service.ApCollectionService;
import qianting.news.cache.CacheService;
import qianting.news.common.constant.BehaviorConstants;
import qianting.news.common.entity.State;
import qianting.news.common.enums.AppHttpCodeEnum;

@Service
@Slf4j
public class ApCollectionServiceImpl implements ApCollectionService {

    @Autowired
    private CacheService cacheService;

    @Override
    public State collection(CollectionBehaviorDto dto) {
        //条件判断
        if(dto == null || dto.getEntryId() == null){
            return State.fail(AppHttpCodeEnum.PARAM_INVALID.getErrorMessage());
        }

        //判断是否登录
        AuthUser user = AppThreadLocalUtil.getUser();
        if(user == null){
            return State.fail(AppHttpCodeEnum.NEED_LOGIN.getErrorMessage());
        }

        //查询
        String collectionJson = (String) cacheService.hGet(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString());
        if(StringUtils.isNotBlank(collectionJson) && dto.getOperation() == 0){
            return State.fail(AppHttpCodeEnum.PARAM_INVALID.getCode(),"已收藏");
        }

        //收藏
        if(dto.getOperation() == 0){
            log.info("文章收藏，保存key:{},{},{}",dto.getEntryId(),user.getId().toString(), JSON.toJSONString(dto));
            cacheService.hPut(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString(), JSON.toJSONString(dto));
        }else {
            //取消收藏
            log.info("文章收藏，删除key:{},{},{}",dto.getEntryId(),user.getId().toString(), JSON.toJSONString(dto));
            cacheService.hDelete(BehaviorConstants.COLLECTION_BEHAVIOR + user.getId(), dto.getEntryId().toString());
        }

        return State.succ(AppHttpCodeEnum.SUCCESS);
    }
}